<?php

class WikiController extends BaseController
{
    public function defaultAction()
    {
        $this->showEdit('/');
    }
    
    public function editAction()
    {
        $path = $this->getParam('path');
        $this->showEdit('/' . trim($path, '/'));
    }

    public function newAction()
    {
        $path = $this->paramExsist('path') ? $this->getParam('path') : '';
        $url = '/' . trim($path, '/');

        if ($_POST['text']) {
            $wiki = new Wiki();
            $wiki->url = trim($url, '/');
            $wiki->text = trim($_POST['text']);
            $wiki->save();
            Url::Redirect($wiki->url);
        }

        $this->view->assign('url', $url);
        $this->view->display('wiki.new.tpl');
    }

    public function showEdit($url)
    {
        $wiki = Wiki::getByUrl($url);
        if ($wiki == null) {
            Url::Redirect('/wiki/new' . $url);
        }

        if (array_key_exists('text', $_POST)) {
            $wiki->text = trim($_POST['text']);
            $wiki->save();
            Url::Redirect($wiki->url);
        }

        $this->view->assign('wiki', $wiki);
        $this->view->display('wiki.edit.tpl');
    }
}